package com.chen.shopping_order_service.service;

import com.chen.shopping_common.pojo.CartGoods;
import com.chen.shopping_common.pojo.Orders;
import com.chen.shopping_common.result.BusException;
import com.chen.shopping_common.result.CodeEnum;
import com.chen.shopping_common.service.OrderService;
import com.chen.shopping_order_service.mapper.CartGoodsMapper;
import com.chen.shopping_order_service.mapper.OrdersMapper;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@DubboService
public class OrderServiceImpl implements OrderService {

    @Autowired
    private CartGoodsMapper cartGoodsMapper;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    private final String CHECK_ORDERS_QUEUE = "check_orders_queue";

    @Override
    public Orders add(Orders orders) {

        /**
         * 设置订单的相关属性
         */
        //设置订单状态未支付
        if (orders.getStatus() == null){
            orders.setStatus(1);
        }

        //设置订单创建时间
        orders.setCreateTime(new Date());
        //计算订单价格，遍历订单所有商品
        //遍历订单商品
        List<CartGoods> cartGoods = orders.getCartGoods();
        //初始化总价
        BigDecimal sum = BigDecimal.ZERO;
        for (CartGoods cartGood : cartGoods) {
            //获取数量
            BigDecimal num = new BigDecimal(cartGood.getNum());
            //获取单价
            BigDecimal price = cartGood.getPrice();
            //单价*数量
            BigDecimal multiply = num.multiply(price);
            //计算总价
            sum = sum.add(multiply);
        }
        orders.setPayment(sum);
        //保存订单
        ordersMapper.insert(orders);
        //保存订单商品到数据库中
        for (CartGoods cartGood : cartGoods) {
            cartGood.setOrderId(orders.getId());
            cartGoodsMapper.insert(cartGood);
        }

        //发送延时消息判断订单状态
        rocketMQTemplate.syncSend(CHECK_ORDERS_QUEUE, MessageBuilder.withPayload(orders.getId()).build(),15000,10);
        return orders;
    }

    @Override
    public void update(Orders orders) {
        ordersMapper.updateById(orders);
    }

    @Override
    public Orders findById(String id) {

        return ordersMapper.findById(id);
    }

    @Override
    public List<Orders> findByUser(Long userId, Integer status) {
        List<Orders> ordersbyUser = ordersMapper.findByUser(userId, status);
        return ordersbyUser;
    }
}
